﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace EFCoreTests.App
{
    public abstract class DbContextBase<TEFTest> : DbContext
        where TEFTest : EFTest<TEFTest>
    {
        public TEFTest Test { get; init; }

        public DatabaseType DatabaseType { get; init; }

        protected DbContextBase(TEFTest test, DatabaseType databaseType)
        {
            Test = test;
            DatabaseType = databaseType;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            switch (DatabaseType)
            {
                case DatabaseType.Sqlserver:
                    optionsBuilder.UseSqlServer(Test.SqlserverConnString);
                    break;
                case DatabaseType.Mysql:
                    optionsBuilder.UseMySql(Test.MysqlConnString, MySqlServerVersion.LatestSupportedServerVersion);
                    break;
            }
            optionsBuilder
                .EnableSensitiveDataLogging()
                .LogTo(Console.WriteLine, LogLevel.Information);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            foreach (var entity in Test.GetEntityTypes())
            {
                modelBuilder.Entity(entity);
            }
            base.OnModelCreating(modelBuilder);
        }
    }
}
